package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/file")
public class DownloadController {

    @RequestMapping("/download1")
    public void download1(HttpServletResponse response) throws Exception {
        System.out.println("DownloadController.download1()");

        response.setHeader("content-disposition",
                new String("attachment;filename=啊.zip".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));


        OutputStream out = null;
        InputStream in = null;


        Resource resource = new ClassPathResource("download/Spring.zip");

        try {
            in = resource.getInputStream();

            out = response.getOutputStream();

            byte[] b = new byte[2048];

            int n;

            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }


    }


    @RequestMapping("/download2")
    public ResponseEntity<byte[]> download2() throws Exception {
        System.out.println("DownloadController.download2()");

        Resource resource = new ClassPathResource("download/Spring.zip");

        HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",new String("Spring啊.zip".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));


        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(resource.getFile()),
                                          headers,
                                          HttpStatus.OK);

    }


}


















